package register

import (
	"errors"
	"cgs-server/server/base"
	"cgs-server/server/model"
	"cgs-server/server/store/sms"
	"cgs-server/server/system/role"
	"cgs-server/server/system/tenant"
	"cgs-server/server/system/user"
	"go.mongodb.org/mongo-driver/bson"
)

type Service interface {
	base.Service

	Register(mdl *model.DataUserModel) error
}

func NewService() Service {
	return &service{
		userRepo: user.NewUserRepository(),
		roleRepo: role.NewRoleRepository(),
	}
}

type service struct {
	base.ServiceImpl
	userRepo user.UserRepository
	roleRepo role.RoleRepository
}

func (s *service) Register(mdl *model.DataUserModel) error {
	vo := mdl.Data.(*RegisterVo)

	// 1. 检查手机号是否已经注册
	one, _ := s.userRepo.FindOne(&model.DataUserModel{
		Data: &model.User{},
		Filter: &bson.M{
			"Phone": vo.PhoneNumber,
			"isDeleted": 0,
		},
	})
	if one != nil {
		return errors.New("该手机号已注册")
	}

	// 校验验证码
	smsCode, _ := sms.GetSmsCode(vo.PhoneNumber)
	if smsCode == nil || smsCode.IsExpired() {
		return errors.New("验证码已过期,请重新发送。")
	}
	if smsCode.Code != vo.ValidationCode {
		return errors.New("验证码不正确")
	}

	userData := &model.User{
		Username: vo.PhoneNumber,
		Phone: vo.PhoneNumber,
		Name: vo.NickName,
		Password: vo.Password,
	}

	tenantService := tenant.NewTenantService()

	if vo.Type == 0 {
		// 新增租户
		tenantVo := &tenant.TenantVo{
			Tenant:    &tenant.Tenant{
				TenantName: vo.TenantName,
			},
			User:     userData,
		}

		err := tenantService.Save(&model.DataUserModel{
			Data: tenantVo,
		})
		if err != nil {
			return err
		}

	} else if vo.Type == 1 {
		// 新增用户
		userData.TenantId = vo.TenantId

		// 查询用户是否存在
		tenantData, _ := tenantService.GetByTenantId(&model.DataUserModel{
			Data: &tenant.Tenant{TenantId: vo.TenantId},
		})

		if tenantData == nil {
			return errors.New("租户不存在")
		}

		// 查询该租户下 普通用户的角色
		roleData, _ := s.roleRepo.FindByRoleAliasOrName(&model.DataUserModel{
			Data: &model.Role{
				RoleAlias: "User",
				TenantModel: model.TenantModel{
					TenantId: vo.TenantId,
				},
			},
		})

		if roleData == nil {
			// 添加一个普通角色
			sort := 0
			roleModel3 := &model.Role{
				RoleName:    "普通用户",
				ParentId:    "0",
				Sort: &sort,
				RoleAlias:   "User",
				TenantModel: model.TenantModel{
					TenantId: vo.TenantId,
				},
				Type: model.BackRole,
			}
			roleService := role.NewRoleService()
			err := roleService.Save(&model.DataUserModel{
				Data: roleModel3,
				User: mdl.User,
			})
			if err != nil {
				return err
			}
			userData.RoleID = roleModel3.GetId()
		} else {
			userData.RoleID = roleData.GetId()
		}

		userService := user.NewUserService()
		err := userService.Save(&model.DataUserModel{
			Data: userData,
		})

		if err != nil {
			return err
		}

	}

	return nil
}



